import { create } from 'zustand';
import { persist, PersistStorage, StorageValue, redux } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import { name } from '../package.json';
import { Draft } from 'immer';
import { DxmState, ProductInfo, ShipmentLimitSecond } from '@/lib/dianxiaomi';
import { generateRandomId } from '@/lib/utils';

const Key = 'CLSTools-' + 'temu' + name;
export const temuStorage = storage.defineItem<StorageValue<State>>(`local:${Key}`);

export interface CategoryItem {
  id: string;
  categoryId: number | '';
  categoryName: string;
  attributes: string;
}

const defaultState: State = {
  currentTabValue: '同步库存',
  isDefaultOpenDialog: true,
  availableSynchronizationSettings: {
    isStopByError: false,
    taskConcurrencyLimit: 5,
  },
  regidtrationActivitySettings: {
    isStopByError: false,
    taskConcurrencyLimit: 5,
  },
  sourceInfoSettings: {
    refreshInterval: 2000,
  },
};

export interface State {
  currentTabValue: string;
  isDefaultOpenDialog: boolean;
  availableSynchronizationSettings: {
    isStopByError: boolean;
    taskConcurrencyLimit: number;
  };
  regidtrationActivitySettings: {
    isStopByError: boolean;
    taskConcurrencyLimit: number;
  };
  sourceInfoSettings: {
    refreshInterval: number;
  };
}

type Actions =
  | {
      type: 'reset';
    }
  | {
      type: 'update';
      update: (draftState: Draft<State>) => void;
    };

const persistStorage: PersistStorage<State> = {
  getItem: async () => {
    const state = await temuStorage.getValue();
    if (!state) {
      return {
        state: defaultState,
        version: 0,
      };
    }
    return state;
  },
  setItem: async (key, newValue) => {
    await temuStorage.setValue(newValue);
  },
  removeItem: (): void => {
    temuStorage.removeValue();
  },
};

const reducer = (state: Draft<State>, action: Actions) => {
  if (action.type === 'reset') {
    return defaultState;
  }
  if (action.type === 'update') {
    const update = action.update;
    update(state);
  }
};

export const useTemuStore = create(
  // @ts-expect-error 因为 immer 导致了 reducer 可以返回 undefiend
  persist(immer(redux(reducer, defaultState)), {
    name: Key,
    storage: persistStorage,
  }),
);
